package com.ysu.concurrency.thread.lock.testLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author 郭辉
 * @className SpinLock
 * @description 自旋锁实现
 * @date 2022/1/12 15:37
 * @company 海康威视
 */
public class SpinLock {
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    /**
     * 加锁
     * */
    public void lock(){
        System.out.println(Thread.currentThread().getName() + "加锁");
        /**
         * 自旋锁
         * */
        while (!atomicReference.compareAndSet(null,Thread.currentThread())){
            System.out.println("--"+Thread.currentThread().getName()+"--");
        }
    }

    /**
     * 解锁
     * */
    public void unlock(){
        System.out.println(Thread.currentThread().getName() + "解锁");
        atomicReference.compareAndSet(Thread.currentThread(),null);
    }
}

/**
 * 测试自定义的自旋锁
 * */
class TestSpinLock{
    public static void main(String[] args) throws InterruptedException {
        SpinLock lock = new SpinLock();

        new Thread(()->{
            lock.lock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (Exception e){
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        },"t1").start();

        TimeUnit.SECONDS.sleep(1);

        new Thread(()->{
            lock.lock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e){
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        },"t2").start();

    }
}
